
#include <iostream>
#include "solutionpool.h"

using namespace std;

solutionpool::~solutionpool()
{
    for (int i = 0; i < SP_MAX_CAPACITY; i++)
    {
        if (thePool[i] != NULL)
             delete thePool[i];
    }
}

void solutionpool::insertSolution(solution* tmpSolution)
{
    tmpSolution->evaluate(trainingSet, testSet);
    tmpSolution->setNumber(nSolNo++);

    int i;
    for (i = 0; i < SP_MAX_CAPACITY; i++)
    {
        if (thePool[i] == NULL)
        {
            thePool[i] = tmpSolution;
            break;
        }
    }
    assert (i < SP_MAX_CAPACITY);

    if (bestSolution == NULL || tmpSolution->getTrainFitness() < bestSolution->getTrainFitness())
    {
        cout << "New Best: ";
        bestSolution = tmpSolution;
        tmpSolution->display();
    }
}

int solutionpool::getCount()
{
    int count = 0;
    for (int i = 0; i < SP_MAX_CAPACITY; i++)
    {
        if (thePool[i] != NULL) count++;
    }
    return count;

}

solution* solutionpool::getRandomSolution()
{
    assert(getCount() > 0);

    int selector = rand() % getCount();

    for (int ndx = 0; ndx < SP_MAX_CAPACITY; ndx++)
    {
        if (thePool[ndx] != NULL)
        {
            if (selector == 0) return thePool[ndx];
            else selector--;
        }
    }
 
    assert(false);
    return NULL;
}
